/*
 * @Author: fisher
 * @Date: 2023-11-13 09:34:31
 * @LastEditTime: 2023-11-24 17:45:05
 * @LastEditors: lbz_dev 1982212843@qq.com
 * @Description:
 * @FilePath: \FCT\src\utils\commen.js
 */
import { imageMap, esri } from "./resource";
import { shenzhenView, defaultView } from "../configs/cesium.config.js";
import { setView } from "./cesium.js";
export const initMap = async () => {
  Cesium.Ion.defaultAccessToken =
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI4NjQwZGMwZi1lYmJjLTQ3NDEtOWNlOS0xN2Q1OWQxYTA2NGUiLCJpZCI6OTA3NjQsImlhdCI6MTY1MDU1MjI5MH0.MkFGfYbFiVIZj0R1gsDA00RjEK-Hf3rux33QQF5MZ0M";
  // 初始化场景
  window.viewer = new Cesium.Viewer("map", {
    // contextOptions: {
    //   requestWebgl1: true,
    // },
    // 去掉默认点选弹窗
    infoBox: false,
    // 去掉左下角动画播放按钮
    animation: false,
    // 去掉右上角搜索按钮
    geocoder: false,
    // 去掉右上角选择底图按钮
    baseLayerPicker: false,
    // 去掉右上角二三维模式切换按钮
    sceneModePicker: false,
    // 去掉右上角返回主视角按钮
    homeButton: false,
    // 去掉右上角帮助说明按钮
    navigationHelpButton: false,
    // 去掉底部时间线
    timeline: false,
    //   去掉右下角全屏按钮
    fullscreenButton: false,
    // 去掉绿色聚焦框
    selectionIndicator: false,
  });
  window.scene = viewer.scene;
  // 去掉底部版本信息
  viewer.bottomContainer.style.display = "none";
  viewer.scene.globe.depthTestAgainstTerrain = true;
  // 添加天地图底图
  viewer.imageryLayers.addImageryProvider(imageMap);
  viewer.scene.debugShowFramesPerSecond = true;
  // 设置初始视角
  // setView(shenzhenView);
  //添加Cesium地形图
  // var terrainProvider = new Cesium.CesiumTerrainProvider({
  //   url: Cesium.IonResource.fromAssetId(1),
  //   requestWaterMask: true, // 请求水体效果所需要的海岸线数据
  //   requestVertexNormals: true, // 请求地形照明数据
  // });
  // viewer.terrainProvider = terrainProvider;
  try {
    const tileset = new Cesium.Cesium3DTileset({
      url: "/mars3d-max-shihua-3dtiles-master/tileset.json",
    });
    window.tileset = tileset;
    tileset.readyPromise.then(function (tileset) {
      viewer.scene.primitives.add(tileset);
      viewer.zoomTo(
        tileset,
        new Cesium.HeadingPitchRange(
          0.0,
          -0.5,
          tileset.boundingSphere.radius * 2.0
        )
      );
    });
  } catch (error) {
    console.error(`Error creating tileset: ${error}`);
  }
// const inverseModelLocal = new Cesium.Matrix4();
// const modelLocal = new Cesium.Matrix4();
// const model = new Cesium.Cesium3DTileset({
//   // url: '../Apps/SampleData/Cesium3DTiles/Tilesets/Tileset/tileset.json',
//   url: '/mars3d-max-shihua-3dtiles-master/tileset.json',
//   customShader: new Cesium.CustomShader({
//     uniforms: {
//       u_inverseLocalModel: {
//         type: Cesium.UniformType.MAT4,
//         value: inverseModelLocal
//       },
//       u_localModel: {
//         type: Cesium.UniformType.MAT4,
//         value: modelLocal
//       },
//       u_planeHeight: {
//         type: Cesium.UniformType.FLOAT,
//         value: -47.9
//       }
//     },
//     vertexShaderText: `
//      void vertexMain(VertexInput vsInput, inout czm_modelVertexOutput vsOutput) {
//        vec4 positionWC = u_inverseLocalModel * czm_model * vec4(vsInput.attributes.positionMC, 1.0);  
//        if (positionWC.z > u_planeHeight) {
//          positionWC.z = u_planeHeight;
//        }
//        vsOutput.positionMC = (czm_inverseModel * u_localModel * positionWC).xyz;   
//     }
//     `,
//   })
// });
// model.readyPromise.then((v) => {
//   viewer.scene.primitives.add(model);
//   const center = v.boundingSphere.center;
//   model.localView = Cesium.Transforms.eastNorthUpToFixedFrame(center, viewer.scene.globe.ellipsoid, modelLocal);      
//   model.localViewInverse = Cesium.Matrix4.inverse(modelLocal, inverseModelLocal);
//  })
//  viewer.flyTo(model)

};

/**
 * @description: 生成id
 * @param {*} len
 * @param {*} radix
 * @return {*}
 */
export const GenerateId = (len, radix) => {
  var chars =
    "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");
  var uuid = [],
    i;
  radix = radix || chars.length;
  if (len) {
    // Compact form
    for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)];
  } else {
    // rfc4122, version 4 form
    var r;

    // rfc4122 requires these characters
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-";
    uuid[14] = "4";

    // Fill in random data.  At i==19 set the high bits of clock sequence as
    // per rfc4122, sec. 4.1.5
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | (Math.random() * 16);
        uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
      }
    }
  }
  return uuid.join("").toLowerCase();
};

/**
 * @description: 针对于id、pid的列表数据形成嵌套树结构
 * @param {Array} list
 * @return {Object} obj
 */
export const list2tree = (list) => {
  console.log("list", list);
  let res = [],
    tempMap = {};
  // 遍历利用Object创建id索引
  list.forEach((item) => {
    tempMap[item.id] = item;
    tempMap[item.id].nodes = [];
  });
  // 再次遍历列表判断遍历项的pid是否存在索引对象tempMap里，存在即新增children，不存在表示当前
  // 为根节点存入最终res数组中
  list.forEach((item) => {
    if (tempMap[item.pid]) {
      tempMap[item.pid].nodes.push(tempMap[item.id]);
    } else {
      res.push(tempMap[item.id]);
    }
  });
  return res;
};
